package com.atguigu.Interceptor;

import com.atguigu.entity.UserInfo;
import com.atguigu.result.Result;
import com.atguigu.result.ResultCodeEnum;
import com.atguigu.util.WebUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @title：
 * @author：Yu
 * @create：2023-02-25 16:36
 * @description：
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session对象:因为该方法没有直接提供session，只提供了request因此用request来获取session对象
        HttpSession session = request.getSession();
        //2.从session中获取数据
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        //3.判断session中是否存在数据
        if (userInfo == null) {
            WebUtil.writeJSON(response, Result.build(null, ResultCodeEnum.LOGIN_AUTH));
            return false;
        }
        return true;
    }
}
